import requests
import json
import numpy as np
import pickle
from collections import defaultdict
import re
from configparser import ConfigParser
import os
from flask import current_app
import time

config = ConfigParser()
config.read('config.ini',encoding='utf-8')
url = config.get('global','url')
username = config.get('global','username')
password = config.get('global','password')
tv_url = config.get('global','tv_url')
psk = config.get('global','psk')

def write_oral(allshows):
    config = ConfigParser()
    config.read('config.ini',encoding='utf-8')
    oral_names = dict(config.items('oral'))
    for ishow in allshows.keys():
        if ishow not in oral_names.values():
            config.set('oral',ishow, ishow)
    with open('config.ini','w',encoding='utf-8') as f:
        config.write(f)


def get_tvshows() -> dict:
    # 从服务器获取电视剧信息
    parameters = {
                  "jsonrpc": "2.0", "method": "VideoLibrary.GetTVShows", 
                  "params": { 
                      "properties": [ "title", "originaltitle",  "playcount", "file", "season", "episode"], 
                      "sort": { "order": "ascending", "method": "label" } 
                  }, 
                  "id": "libTvShows"
                 }
    json_all_tvshows = requests.post(url,json=parameters,auth=(username,password)).json()
    dict_all_tvshows = dict()
    for itvshow in json_all_tvshows['result']['tvshows']:
        # store tvshowid , number of seasons, number of total episode
        tvshow_info = dict()
        tvshow_info['basic'] = ((itvshow['tvshowid'],itvshow['season'],itvshow['episode']))
        # get all episode id into a array
        parameters2 = {
                  "jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", 
                  "params": { 
                      "tvshowid":itvshow['tvshowid'],
                      "properties": ["title", "originaltitle", "season", "file","episode","showtitle"], 
    #                   "limits": { "start" : 0, "end": 75 }, 
                      "sort": { "order": "ascending", "method": "label" } 
                  }, 
                  "id": "libEpisodes"
                 }
        json_episodes = requests.post(url,json=parameters2,auth=(username,password)).json()
    #    print(itvshow['title'],json_episodes['result'].keys())
    #     episodes_id = np.zeros((itvshow['season'],itvshow['episode']))
        try:
            episodes = [(iepisode['season'],iepisode['episode'],iepisode['episodeid']) for iepisode in json_episodes['result']['episodes']]
            tvshow_info['detail'] = episodes
            episodes_index = defaultdict(list)
            for ie in episodes:
                # if ie[1] == len(episodes_index[f"{ie[0]:04d}"])+1:
                if ie[1] == len(episodes_index["{0:04d}".format(ie[0])])+1:
                    episodes_index["{0:04d}".format(ie[0])].append(ie[2])
                else:
                    # 如果下一个的episode和已经存储的不连续，那么先添加-1填充
                    # for i in range(ie[1] - len(episodes_index[f"{ie[0]:04d}"]) -1 ):
                    for i in range(ie[1] - len(episodes_index["{0:04d}".format(ie[0])]) -1 ):
                        episodes_index["{0:04d}".format(ie[0])].append(-1)
                    episodes_index["{0:04d}".format(ie[0])].append(ie[2])

            tvshow_info['index'] = episodes_index        
            dict_all_tvshows[itvshow['title']] = tvshow_info   
        except Exception as e:
            print(itvshow['title'])
            print(e.message)
    return dict_all_tvshows


def store(data):
    # save result
    with open("dict_all_tvshows","wb") as f:
        pickle.dump(data,f)


def read_data():
    if os.path.exists("dict_all_tvshows"):
        with open("dict_all_tvshows","rb") as f:
            result = pickle.load(f)
    else:
        result = get_tvshows()
        store(result)
    return result


def calc_index(data):
    # calculate the index for dict_all_tvshows
    for ishow in data:
        episodes = defaultdict(list)
        for ie in data[ishow]['detail']:
            if ie[1] == len(episodes["{0:04d}".format(ie[0])])+1:
                episodes["{0:04d}".format(ie[0])].append(ie[2])
            else:
                # 如果下一个的episode和已经存储的不连续，那么先添加-1填充
                for i in range(ie[1] - len(episodes["{0:04d}".format(ie[0])]) -1 ):
                    episodes["{0:04d}".format(ie[0])].append(-1)
                episodes["{0:04d}".format(ie[0])].append(ie[2])

        data[ishow]['index'] = episodes
    return data

def get_resume(episodeid:int) -> int:
    # get the seconds the episode had been played and total time
    # return position,total in seconds
    parameters4 = {
                "jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodeDetails", 
                "params": {
                    "episodeid":episodeid,
                    "properties":["resume","title"]
                    }, 
                "id": 1
                }
    result4= requests.post(url,json=parameters4,auth=("kodi","kodi")).json()
    return int(result4['result']['episodedetails']['resume']['position']), \
    int(result4['result']['episodedetails']['resume']['total'])

def play_resume(episodeid:int):
    # play what's remaining for episodeid
    position,total = get_resume(episodeid)
    result = play_episode(episodeid)
    if result == "OK":
        # pause and seek
        time.sleep(1)
        parameters3 = {
                "jsonrpc": "2.0", "method": "Player.Seek", 
                "params": {
                    "playerid":1,
                    "value":{"seconds":position}                  
                    }, 
                "id": 1
                }
        result3= requests.post(url,json=parameters3,auth=("kodi","kodi")).json()
        if "result" in result3:
            return "OK","Starts from {} s".format(position)
        else:
            return "Can't Seek",None
    else:
        return "Can't play",None

def play_episode(episodeid: int) -> str:
    parameters3 = {
              "jsonrpc": "2.0", "method": "Player.Open", 
              "params": {
                  "item":{"episodeid":episodeid}                  
                }, 
              "id": 1
             }

    try:
        result3= requests.post(url,json=parameters3,auth=(username,password),timeout=2).json()
        return result3['result']
    except Exception as e:
        print("Can't connect, with error",e)
        return "Can't connect"

def scan_library():
    parameters6 = {
              "jsonrpc": "2.0", "method": "VideoLibrary.Scan", 
              "params": {                  
                }, 
              "id": 1
             }

    try:
        result6= requests.post(url,json=parameters6,auth=(username,password)).json()
        return result6["result"]
    except Exception as e:
        print("Can't connect")
        return "Can't connect"

def stop_playing():
    parameters6 = {
              "jsonrpc": "2.0", "method": "Player.GetActivePlayers", 
              "params": {                  
                }, 
              "id": 1
             }

    try:
        result6= requests.post(url,json=parameters6,auth=(username,password)).json()
        playerid = result6["result"][0]["playerid"]
        print("playerid is ",playerid)
        parameter5 = {
              "jsonrpc": "2.0", "method": "Player.Stop", 
              "params": {                  
                "playerid":playerid
                }, 
              "id": 1

            }
        result5= requests.post(url,json=parameter5,auth=(username,password)).json()
        print(result5)
        return result5["result"]
    except Exception as e:
        print("Can't connect")
        return "Can't connect"

def pause_playing():
    parameters6 = {
              "jsonrpc": "2.0", "method": "Player.GetActivePlayers", 
              "params": {                  
                }, 
              "id": 1
             }

    try:
        result6= requests.post(url,json=parameters6,auth=(username,password)).json()
        playerid = result6["result"][0]["playerid"]
        print("playerid is ",playerid)
        parameter5 = {
              "jsonrpc": "2.0", "method": "Player.PlayPause", 
              "params": {                  
                "playerid":playerid
                }, 
              "id": 1

            }
        result5= requests.post(url,json=parameter5,auth=(username,password)).json()
        print(result5)
        return result5["result"]
    except Exception as e:
        print("Can't connect")
        return "Can't connect"

def get_playing():
    parameters6 = {
              "jsonrpc": "2.0", "method": "Player.GetActivePlayers", 
              "params": {                  
                }, 
              "id": 1
             }

    try:
        result6= requests.post(url,json=parameters6,auth=(username,password)).json()
        playerid = result6["result"][0]["playerid"]
        parameters7 = {
                "jsonrpc": "2.0", "method": "Player.GetItem", 
                "params": {
                    "playerid":playerid,
                    "properties":[ "season", "episode","showtitle"]
                    }, 
                "id": 1
                }
        result7 = requests.post(url,json=parameters7,auth=(username,password)).json()
        showtitle = result7['result']['item']['showtitle']
        nseason = result7['result']['item']['season']
        nepisode = result7['result']['item']['episode']
        return showtitle,nseason,nepisode
    except Exception as e:
        print("Can't get playing")
        return None,None,None

def parse_volume(command):
    pattern_vol = re.compile("音量(.*)")
    match_vol = pattern_vol.search(command)
    content = match_vol.groups()[0]
    modes = [
        ("调高(.*)","+"),
        ("调大(.*)","+"),
        ("提高(.*)","+"),
        ("提大(.*)","+"),
        ("增大(.*)","+"),
        ("调低(.*)","-"),
        ("调小(.*)","-"),
        ("降低(.*)","-"),
        ("减小(.*)","-"),
        ("减小(.*)","-"),
        ("调到(.*)",""),
        ("设为(.*)",""),
    ]
    for ip,ia in modes:
        pattern = re.compile(ip)
        if pattern.search(content):
            match_content = pattern.search(content)
            direction = ia
            break
    # get value
    str_value = match_content.groups()[0]
    if str_value =="":
        value = 1
    else:
        value = number(str_value)
    return "{0}{1}".format(direction,value)

def parse_play(command):
    tvshow = None
    season = None
    episode = None
    pattern = re.compile("播放(.*)")
    pattern_episode = re.compile("(.*)第(.*)集")
    pattern_season = re.compile("(.*)第(.*)季")
    match_play = pattern.search(command)
    if match_play:
        whatplay = match_play.groups()[0]
        match_episode = pattern_episode.search(whatplay)
        if match_episode:
            episode = match_episode.groups()[1]
            whatplay = match_episode.groups()[0]
        match_season = pattern_season.search(whatplay)
        if match_season:
            season = match_season.groups()[1]
            tvshow = match_season.groups()[0]
        else:
            tvshow = whatplay
        return [tvshow,season,episode]
    else:
        # 没找到播放关键字
        return None

def parse_offset(command):
    # parse 上一集/下一集
    tvshow = None
    offset = 0
    pattern_pre = re.compile("上一集(.*)")
    pattern_next = re.compile("下一集(.*)")
    match_pre = pattern_pre.search(command)
    match_next = pattern_next.search(command)
    if match_pre:
        offset = -1
        tvshow = match_pre.groups()[0]
        if tvshow == "":
            tvshow = None
    if match_next:
        offset = 1
        tvshow = match_next.groups()[0]
        if tvshow == "":
            tvshow = None
    return tvshow,offset


def parse_command(command) ->str :
    # parse command
    action = None
    modes = [
        ("播放(.*)","play"),
        ("下一集(.*)","next"),
        ("上一集(.*)","previous"),
        ("更新(.*)","scan"),
        ("不看了(.*)","stop"),
        ("不看啦(.*)","stop"),
        ("暂停(.*)","pause"),
        ("继续(.*)","continue"),
        ("有什么(.*)","showall"),
        ("打开电视(.*)","turnon"),
        ("关电视(.*)","turnoff"),
        ("音量(.*)","setvolume"),
        ("树莓派(.*)","kodi"),
        ("盒子(.*)","n1"),
    ]
    for ip,ia in modes:
        pattern = re.compile(ip)
        if pattern.search(command):
            action = ia
            break
    # pattern_play = re.compile("播放(.*)")
    # pattern_play_next = re.compile("下一集(.*)")
    # pattern_play_previous = re.compile("上一集(.*)")
    # pattern_scan = re.compile("更新(.*)")
    # pattern_stop = re.compile("不看了(.*)")
    # pattern_stop2 = re.compile("不看啦(.*)")
    # pattern_pause = re.compile("暂停(.*)")
    # pattern_continue = re.compile("继续(.*)")
    # pattern_showall = re.compile("有什么(.*)")
    # pattern_turnon = re.compile("打开电视(.*)")
    # pattern_turnoff = re.compile("关电视(.*)")
    # match_play = pattern_play.search(command)
    # match_play_next = pattern_play_next.search(command)
    # match_play_previous = pattern_play_previous.search(command)
    # match_scan = pattern_scan.search(command)
    # match_stop = pattern_stop.search(command)
    # match_stop2 = pattern_stop2.search(command)
    # match_pause = pattern_pause.search(command)
    # match_continue = pattern_continue.search(command)
    # match_showall = pattern_showall.search(command)
    # match_turnon = pattern_turnon.search(command)
    # match_turnoff = pattern_turnoff.search(command)
    # if match_play:
    #     action = "play"
    # elif match_play_next:
    #     action = "next"
    # elif match_play_previous:
    #     action = "previous"
    # elif match_scan:
    #     action = "scan"
    # elif match_stop or match_stop2:
    #     action = "stop"
    # elif match_continue:
    #     action = "continue"
    # elif match_pause:
    #     action = "pause"
    # elif match_showall:
    #     action = "showall"
    return action

    

def number(n_str:str) -> int:
    # turn string number into int, string number could be chinese character
    chinese_num = ["零","一","二","三","四","五","六","七","八","九","十","百","千","万"]
    num  = [0,1,2,3,4,5,6,7,8,9,10,100,1000,10000]
    try:
        result = int(n_str)
    except ValueError:
        # for chinese character
        num_digit = [] # 位上的数字
        num_multy = [] # 乘子
        for i,istr in enumerate(n_str):
            try:
                if chinese_num.index(istr)<=9:
                    num_digit.append(num[chinese_num.index(istr)])                          
                else:
                    num_multy.append(num[chinese_num.index(istr)])
            except ValueError:
                # the character is not in chinese_num,return 1 for robust
                return 1
            if i==len(n_str)-1:
                num_multy.append(1)
        num_digit = np.pad(np.array(num_digit),(len(num_multy)-len(num_digit),0),'constant',constant_values=1)
        num_multy = np.array(num_multy)
        result = np.dot(num_digit,num_multy)
    return result

def parse_tvshow_name(name:str) ->str:
    # 把口语上的剧集名字转换为数据库中的名字
    config = ConfigParser()
    config.read('config.ini',encoding='utf-8')
    oral_names = dict(config.items('oral'))
    try:
        database_name = oral_names[name]
    except KeyError as e:
        print("{0} is not in oral names dict".format(name))
        database_name = name
    return database_name

def parse_oral_name(name:str) -> str:
    # 把数据库中的名字转成口令中的名字
    config = ConfigParser()
    config.read('config.ini',encoding='utf-8')
    reverse = defaultdict(list)
    for ipair in config.items('oral'):
        # ipair=(oral_name,database_name)
        reverse[ipair[1]].append(ipair[0])   
    try:
        oral_name = reverse[name]
    except KeyError as e:
        print("{0} is not in dataset".format(name))
        oral_name = name
    return ",".join(oral_name)



def get_episodeid(command,dict_all_tvshows):
    result = parse_play(command)
    if result[0] is None:
        return None,"Error"
    else:
        tvshow_name = parse_tvshow_name(result[0])
        if tvshow_name in dict_all_tvshows.keys():
            if result[1] is None:
                # play random episode
                pick = np.random.randint(0,len(dict_all_tvshows[tvshow_name]['detail']),size=(1))[0]
                # return dict_all_tvshows[tvshow_name]['detail'][pick][2],f"播放{tvshow_name}第{dict_all_tvshows[tvshow_name]['detail'][pick][0]}季第{dict_all_tvshows[tvshow_name]['detail'][pick][1]}集"
                return dict_all_tvshows[tvshow_name]['detail'][pick][2],"播放{0}第{1}季第{2}集".format(tvshow_name,dict_all_tvshows[tvshow_name]['detail'][pick][0],dict_all_tvshows[tvshow_name]['detail'][pick][1])
            else:
                ns = number(result[1])
                if result[2] is None:
                    # play random episode for the given season
                    episodeid = np.random.choice(dict_all_tvshows[tvshow_name]['index'][f"{ns:04d}"])
                    return episodeid,"播放{0}第{1}季第{2}集".format(tvshow_name,ns,dict_all_tvshows[tvshow_name]['index']['{0:04d}'.format(ns)].index(episodeid))
                else:
                    # play given episode from given season                  
                    ne = number(result[2])
                    episodeid = dict_all_tvshows[tvshow_name]['index']['{0:04d}'.format(ns)][ne-1]
                    return episodeid,"播放{0}第{1}季第{2}集".format(tvshow_name,ns,ne)

        else:
            return None,"Error"

def get_offset_episodeid_from_playing(dict_all_tvshows,offset=1):
    # get offset episode from playing, offset =1 means next
    # result is what last played, it should not be None
    tvshow_name,nseason,nepisode = get_playing()
    if tvshow_name is None:
        return None,"Error"
    else:
        if tvshow_name in dict_all_tvshows.keys():
            if nseason is None:
                # play random episode
                pick = np.random.randint(0,len(dict_all_tvshows[tvshow_name]['detail']),size=(1))[0]
                # return dict_all_tvshows[tvshow_name]['detail'][pick][2],f"播放{tvshow_name}第{dict_all_tvshows[tvshow_name]['detail'][pick][0]}季第{dict_all_tvshows[tvshow_name]['detail'][pick][1]}集"
                return dict_all_tvshows[tvshow_name]['detail'][pick][2],"播放{0}第{1}季第{2}集".format(tvshow_name,dict_all_tvshows[tvshow_name]['detail'][pick][0],dict_all_tvshows[tvshow_name]['detail'][pick][1])
            else:
                if nepisode is None:
                    # play random episode for the given season
                    episodeid = np.random.choice(dict_all_tvshows[tvshow_name]['index'][f"{ns:04d}"])
                    return episodeid,"播放{0}第{1}季第{2}集".format(tvshow_name,ns,dict_all_tvshows[tvshow_name]['index']['{0:04d}'.format(nseason)].index(episodeid))
                else:
                    # get next play
                    for icount,(ins,ine,ieid) in enumerate(dict_all_tvshows[tvshow_name]['detail']):
                        if (ins == nseason) and (ine == nepisode):
                            # this is what last played
                            index = icount
                            break
                    total = len(dict_all_tvshows[tvshow_name]['detail'])
                    if index + offset > total - 1:
                        findex = total - 1
                    elif index + offset < 0:
                        findex = 0
                    else:
                        findex = index + offset
                    fns,fne,episodeid = dict_all_tvshows[tvshow_name]['detail'][findex]
                    return episodeid,"播放{0}第{1}季第{2}集".format(tvshow_name,fns,fne)
        else:
            return None,"Error"

def get_offset_episodeid(last_command,dict_all_tvshows,offset=1):
    # get offset episode from last command, offset default is 1, which means next episode
    # result is what last played, it should not be None
    result = parse_play(last_command)
    if result[0] is None:
        return None,"Error"
    else:
        tvshow_name = parse_tvshow_name(result[0])
        if tvshow_name in dict_all_tvshows.keys():
            if result[1] is None:
                # play random episode
                pick = np.random.randint(0,len(dict_all_tvshows[tvshow_name]['detail']),size=(1))[0]
                # return dict_all_tvshows[tvshow_name]['detail'][pick][2],f"播放{tvshow_name}第{dict_all_tvshows[tvshow_name]['detail'][pick][0]}季第{dict_all_tvshows[tvshow_name]['detail'][pick][1]}集"
                return dict_all_tvshows[tvshow_name]['detail'][pick][2],"播放{0}第{1}季第{2}集".format(tvshow_name,dict_all_tvshows[tvshow_name]['detail'][pick][0],dict_all_tvshows[tvshow_name]['detail'][pick][1])
            else:
                ns = number(result[1])
                if result[2] is None:
                    # play random episode for the given season
                    episodeid = np.random.choice(dict_all_tvshows[tvshow_name]['index'][f"{ns:04d}"])
                    return episodeid,"播放{0}第{1}季第{2}集".format(tvshow_name,ns,dict_all_tvshows[tvshow_name]['index']['{0:04d}'.format(ns)].index(episodeid))
                else:
                    # get next play
                    ne = number(result[2])
                    for icount,(ins,ine,ieid) in enumerate(dict_all_tvshows[tvshow_name]['detail']):
                        if (ins == ns) and (ine == ne):
                            # this is what last played
                            index = icount
                            break
                    total = len(dict_all_tvshows[tvshow_name]['detail'])
                    if index + offset > total - 1:
                        findex = total - 1
                    elif index + offset < 0:
                        findex = 0
                    else:
                        findex = index + offset
                    fns,fne,episodeid = dict_all_tvshows[tvshow_name]['detail'][findex]
                    return episodeid,"播放{0}第{1}季第{2}集".format(tvshow_name,fns,fne)
        else:
            return None,"Error"

class CommandHistory():
    def __init__(self, length_max:int = 10):
        self.history = list()
        self.LENGTH_MAX = length_max

    def push(self,command:str,action:str):
        # push one command into history  
        if len(self.history) < self.LENGTH_MAX:
            self.history.append((command,action))
        else:
            del self.history[0]
            self.history.append((command,action))
    
    def get_last_play(self):
        # get last command play, return none is not found
        result = None
        if len(self.history) > 0:
            for command,action in self.history[::-1]:
                if action == 'play':
                    result = command 
                    break
        return result

def tvwol():
    # try to wake tv on lan
    status = False
    url = "{0}:80/sony/system".format(tv_url)
    parameter = {
        "method": "getSystemInformation",
        "id": 33,
        "params": [],
        "version": "1.0"
    } 
    header = {
        'X-Auth-PSK':psk
    }
    for i in range(10):
        try:
            result4= requests.post(url,json=parameter,headers=header,timeout=1).json()
            if result4['result'] != []:
                status = True
                break
        except:
            current_app.logger.info("Trying to wake tv for {0} times".format(i))
    return status




def tvstatus():
    # get current power status
    url = "{0}:80/sony/system".format(tv_url)
    parameter = {
        "method": "getPowerStatus",
        "id": 50,
        "params": [],
        "version": "1.0"
    } 
    header = {
        'X-Auth-PSK':psk
    }
    result4= requests.post(url,json=parameter,headers=header).json()
    status = result4['result'][0]['status']
    return status

def tvturnon():
    # turn on tv if it's down
    status = tvstatus()
    if status == 'standby':
        url = "{0}:80/sony/system".format(tv_url)
        parameter = {
            "method": "setPowerStatus",
            "id": 55,
            "params": [{"status": True}],
            "version": "1.0"
                    }
        header = {
            'X-Auth-PSK':psk
        }
        wake = tvwol()
        if wake: # tv is wake
            result4= requests.post(url,json=parameter,headers=header).json()
            if result4['result'] ==[]:
                return True,"电视已打开"
            else:
                return False,"电视未能打开，稍后再试"
        else:
            return False,"电视未能唤醒，稍后再试"
    else:
        return False,"电视已打开"

def tvturnoff():
    status = tvstatus()
    if status == 'active':
        url = "{0}:80/sony/system".format(tv_url)
        parameter = {
            "method": "setPowerStatus",
            "id": 55,
            "params": [{"status": False}],
            "version": "1.0"
                    }
        header = {
            'X-Auth-PSK':psk
        }
        wake = tvwol()
        if wake: # tv is wake
            result4= requests.post(url,json=parameter,headers=header).json()
            if result4['result'] == []:
                return True,"电视已关闭"
            else:
                return False,"电视未能关闭，稍后再试"
        else:
            return False,"电视未能唤醒，稍后再试"
    else:
        return False,"电视未打开"


def tvsetvolume(command):
    status = tvstatus()
    if status == 'active':
        value = parse_volume(command)
        url = "{0}:80/sony/audio".format(tv_url)
        parameter = {   
            "method": "setAudioVolume",
            "id": 601,
            "params": [{
                "volume": value,
                "target": "speaker"
            }],
            "version": "1.0"
                    }
        header = {
            'X-Auth-PSK':psk
        }
        wake = tvwol()
        if wake: # tv is wake
            result4= requests.post(url,json=parameter,headers=header).json()
            if result4['result'] ==[0]:
                return True,"音量已设定"
            else:
                return False,"未能调整音量，稍后再试"
        else:
            return False,"电视未能唤醒，稍后再试"
    else:
        return False,"电视未打开"

def tvsetinput(number:int):
    status = tvstatus()
    if status == 'active':
        url = "{0}:80/sony/avContent".format(tv_url)
        parameter = {   
            "method": "setPlayContent",
            "id": 101,
            "params": [{"uri": "extInput:hdmi?port={0}".format(number)}],
            "version": "1.0"
                    }
        header = {
            'X-Auth-PSK':psk
        }
        wake = tvwol()
        if wake: # tv is wake
            result4= requests.post(url,json=parameter,headers=header).json()
            if result4['result'] ==[]:
                return True,"已切换输入源"
            else:
                return False,"未能切换输入源，稍后再试"
        else:
            return False,"电视未能唤醒，稍后再试"
    else:
        return False,"电视未打开"


if __name__ == "__main__":
    # print(parse_command(command="不看啦"))
    # print(parse_command(command="更新"))
    # print(parse_command(command="播放浪漫史"))
    # print(parse_command(command="打开电视"))
    # print(tvstatus())
    # print(parse_volume("音量设为30"))
    # print(parse_volume("音量降低八"))
    # print(parse_volume("音量增大十八"))
    # print(parse_volume("音量降低"))
    # print(parse_tvshow_name("寻妈记"))
    # print(parse_tvshow_name("浪漫史"))
    # tvshows = read_data()
    # print(tvshows.keys())
    data = read_data()
    command = "播放火线第2季第2集"
    print(get_resume(get_episodeid(command,data)[0]))
    # print(get_episodeid(command,data))
